package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.DimensionsApi;
import com.tanhua.model.mongo.Dimension;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.List;

@DubboService
public class DimensionsApiImpl implements DimensionsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Dimension> findDimensionsList(ObjectId id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("reportId").is(id));
        List<Dimension> dimensions = mongoTemplate.find(query, Dimension.class);
        return dimensions;
    }

    @Override
    public void addAndUpdateDimension(List<Dimension> dimensionList) {
        Query query=new Query();
        query.addCriteria(Criteria.where("reportId").is(dimensionList.get(0).getReportId()));
        List<Dimension> dimensions = mongoTemplate.find(query, Dimension.class);

        if(!CollectionUtils.isEmpty(dimensions)) {
            //不为空 则先删除原来的记录
            mongoTemplate.remove(query,Dimension.class);
        }
        // 批量插入
        mongoTemplate.insertAll(dimensionList);
    }
}
